package com.dragon.pear.modules.trade.common.config;

import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.oas.models.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.web.method.HandlerMethod;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Chris Chan
 * Create On 2025/10/1 下午12:41
 * Use for:
 * Explain:
 */
@Slf4j
//@Configuration
public class TradeOpenApiConfig {

    @Bean
    public GroupedOpenApi trade2() {
        return GroupedOpenApi.builder()
                .group("trade")
                .displayName("97. 交易")
//                .packagesToScan("com.dragon.pear.modules.trade")
                .addOperationCustomizer(new OperationCustomizer() {
                    @Override
                    public Operation customize(Operation operation, HandlerMethod method) {
                        boolean support = OpenApiUtil.isSupport(method, "trade");
                        log.info("thread={},operation-beanType:{},operation-summer:{},是否标记:{}", Thread.currentThread().getName(), method.getBeanType().getName(), operation.getSummary(), support);
                        if (support) {
                            // 标记
                            operation.addExtension("x-api-group", "trade");
                        }
                        return operation;
                    }
                })
                .addOpenApiCustomizer(openApi -> {
                    // 重新收集
                    Paths paths = new Paths();

                    // 遍历所有路径
                    openApi.getPaths().forEach((path, pathItem) -> {
                        // 处理所有HTTP方法
                        pathItem.readOperationsMap().forEach((httpMethod, operation) -> {
                            Map<String, Object> extensions = operation.getExtensions();
                            String apiGroup = (String) extensions.get("x-api-group");
                            if (Objects.equals(apiGroup, "trade")) {
                                log.info("path={}, httpMethod={}, apiGroup={}", path, httpMethod, apiGroup);
                                paths.addPathItem(path, pathItem);


                            }
                        });
                    });
                    // 替换旧的 paths
                    openApi.setPaths(paths);


                })
                .build();
    }
}
